import urllib.parse
import datetime
import requests
import json

from coin.base.datetime_util import to_timestamp_int


class CosmosNativePrivateClient:
  def __init__(self,
               *,
               node_info,
               api_key=None,
               timeout=60):
    self._host = node_info
    self._api_key = api_key
    self._timeout = timeout

  def _get(self, host, path, params=None):
    url = urllib.parse.urljoin(host, path)
    response = requests.request('GET',
                                url,
                                params=params,
                                timeout=self._timeout)
    response.raise_for_status()
    content = response.json()
    return content

  def get_block_timestamp(self, block_number):
    response = self._get(self._host, f'blocks/{block_number}')
    block_header = response['block']['header']
    block_time = to_timestamp_int(
      datetime.datetime.strptime(
      block_header['time'].split('.')[0],
      '%Y-%m-%dT%H:%M:%S'))
    return block_time

  def get_latest_block_number_timestamp(self):
    response = self._get(self._host, 'blocks/latest')
    block_header = response['block']['header']
    block_time = to_timestamp_int(
      datetime.datetime.strptime(
      block_header['time'].split('.')[0],
      '%Y-%m-%dT%H:%M:%S'))
    block_num = int(block_header['height'])
    return block_num, block_time

  def get_latest_balance(self, address):
    response = self._get(self._host, f'/bank/balances/{address}')
    if response is None:
      raise requests.exceptions.RequestException
    if 'result' not in response:
      raise ValueError(response)
    return response['result']

  def get_token_balance(
      self,
      address,
      token_address,
      end_height=None
  ):
    balances = self.get_latest_balance(address)
    balance_sum = 0
    for balance in balances:
      if token_address == balance['denom']:
        balance_sum += float(balance['amount'])
    return balance_sum
